import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/order_provider.dart';
import '../../../utils/g.dart';
import '../../../utils/payment.dart';

class OrderBottomMenu extends StatefulWidget {
  const OrderBottomMenu({Key? key}) : super(key: key);

  @override
  _OrderBottomMenuState createState() => _OrderBottomMenuState();
}

class _OrderBottomMenuState extends State<OrderBottomMenu> {
  Map order = {};
  Map orderPrice = {};

  @override
  Widget build(BuildContext context) {
    order = Provider.of<OrderProvider>(context, listen: false).order;
    orderPrice = Provider.of<OrderProvider>(context).computedPrice;
    // print(orderPrice);

    return Row(
      children: [
        Container(
          width: G.width / 2 + 30,
          height: 50,
          color: Colors.green,
          alignment: Alignment.center,
          child: Text(
            "总计：￥"+orderPrice['pay_price'].toString(),
            style: const TextStyle(
              color: Colors.white,
              fontSize: 24
            )
          ),
        ),
        InkWell(
          onTap: () {
            // 弹出支付方式窗口
            _getPaymentDialog(context);
          },
          child: Container(
            width: G.width / 2 - 30,
            height: 50,
            color: Theme.of(context).primaryColor,
            alignment: Alignment.center,
            child: const Text(
              '立即结算',
              style: TextStyle(
                color: Colors.white,
                fontSize: 24
              )
            )
          ),
        )
      ],
    );
  }

  void _getPaymentDialog(context) {
    showModalBottomSheet(
      context: context, 
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        )
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext ctx, StateSetter stateSetter) {
            return Stack(
              children: [
                Column(
                  children: [
                    _getPaymentHeader(),
                    _getPaymentBody(context, stateSetter),
                    _getPaymentFooter()
                  ],
                ),
                Positioned(
                  left: 0,
                  bottom: 0,
                  child: InkWell(
                    onTap: () async {
                      // 前往订单确认页面
                      var payType = Provider.of<OrderProvider>(context, listen: false).payment;
                      var address = Provider.of<OrderProvider>(context, listen: false).address;
                      var coupon = Provider.of<OrderProvider>(context, listen: false).coupon;
                      var useIntegral = Provider.of<OrderProvider>(context, listen: false).useIntegral;
                      var remark = Provider.of<OrderProvider>(context, listen: false).remark;
                      var res = await G.api.order.create(
                        key: order['orderKey'], 
                        addressId: address['id'], 
                        payType: payType,
                        couponId: coupon['id'] ?? 0,
                        useIntegral: useIntegral ? 1 : 0,
                        remark: remark
                      );
                      if (res != null && res['status'] == 200) {
                        // print('支付成功');
                        // 跳转到订单支付页面
                        Future.delayed(const Duration(milliseconds: 400), () {
                          Map<String, String> p = {
                            "uni": res['data']['result']['orderId'].toString()
                          };
                          G.router.navigateTo(context, '/order_pay'+G.parseQuery(params: p));
                        });

                      } else {
                        G.error('支付失败');
                      }
                    },
                    child: Container(
                      width: G.width,
                      height: 50,
                      color: Colors.green,
                      alignment: Alignment.center,
                      child: const Text(
                        "去付款",
                        style: TextStyle(
                          fontSize: 24,
                          color: Colors.white
                        )
                      ),
                    )
                  )
                )
              ],
            );
          }
        );
      }
    );
  }

  Widget _getPaymentHeader() {
    return Container(
      margin: const EdgeInsets.all(20),
      child: const Center(
        child: Text(
          '选择支付方式',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.w500
          )
        )
      ),
    );
  }

  Widget _getPaymentBody(context, stateSetter) {
    var p = Provider.of<OrderProvider>(context).payment;
    List payment = getPayment();

    return Container(
      margin: const EdgeInsets.fromLTRB(20, 0, 20, 5),
      child: Column(
        children: payment.map<Widget>((item) {
          return RadioListTile(
            value: item['value'], 
            groupValue: p, 
            onChanged: (dynamic value) {
              // 触发支付方式状态的变更
              Provider.of<OrderProvider>(context, listen: false).setPayment(value.toString());

            },
            title: Text(item['name']),
            secondary: Image.asset(
              item['icon'],
              width: 50,
              height: 50,
            ),
            selected: p == item['value'],
            contentPadding: const EdgeInsets.all(5),
          );
        }).toList()
      ),
    );
  }

  Widget _getPaymentFooter() {
    return Container(
      margin: const EdgeInsets.fromLTRB(20, 5, 20, 40),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Text('支付：'),
          Text(
            "￥ "+orderPrice['pay_price'].toString(),
            style: const TextStyle(
              fontSize: 24,
              fontWeight: FontWeight.w500,
              color: Colors.red
            )
          )
        ],
      ),
    );
  }
}